package com.deneme.ozveri.activities;

import java.util.ArrayList;
import java.util.Hashtable;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.ScrollView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.deneme.ozveri.adapters.CheckBoxGridAdapter;

import com.deneme.ozveri.application.OzveriMenuApplicationObject;
import com.deneme.ozveri.clicklisteners.TitleBarOnClickListener;
import com.deneme.ozveri.objects.MenuOrderItem;
import com.deneme.ozveri.objects.MenuOrderItemExtras;
import com.deneme.ozverimenu.R;

public class OrderDetailActivity extends Activity {

	int orderId;
	MenuOrderItem item;

	TextView price;
	Spinner quantity;
	TextView desc;
	TextView name;
	LinearLayout extrasMain;
	GridView extrasGrid;
	Button addCart;
	ScrollView mainView;

	ArrayList<CheckBox> checklist;
	ArrayList<LinearLayout> multilist;
	ArrayList<String> radioGroupNames;
	Hashtable<Integer,RadioGroup> radioGroups;


	@Override
	protected void onCreate(Bundle savedInstanceState) {


		
    	/**************************Custon Titlebar init**********************/
		requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
		setContentView(R.layout.order_detail);
		getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.titlebar);
		
		
		TitleBarOnClickListener titlebarlistener = new TitleBarOnClickListener(this);
		
		Button openOrders = (Button) findViewById(R.id.titlebar_orders_btn);
		openOrders.setOnClickListener(titlebarlistener);
		/*******************************************************************/
		
		
		price = (TextView) findViewById(R.id.orderdetail_price_txt);
		quantity = (Spinner) findViewById(R.id.orderdetail_quantity_spinner);
		desc = (TextView) findViewById(R.id.orderdetail_detail_txt);
		name = (TextView) findViewById(R.id.orderdetail_name_txt);
		extrasMain = (LinearLayout) findViewById(R.id.orderdetail_extras_linear);
		extrasGrid = (GridView) findViewById(R.id.orderdetail_extras_grid);
		addCart = (Button) findViewById(R.id.orderdetail_orderitems_btn);
		mainView = (ScrollView) findViewById(R.id.orderdetail_main_scroll);



		orderId = getIntent().getExtras().getInt("id");		
		item = OzveriMenuApplicationObject.dh.getOrderItem(orderId);

		desc.setText(item.getOrderDescription());
		name.setText(item.getOrderName());
		
		String[] np = new String[25];
		for(int i=0;i<25;i++){
			np[i]=Integer.toString(i+1);
		}
		
		ArrayAdapter <String> adapter = new ArrayAdapter<String>(this, R.layout.spinner_item_text, np);
		quantity.setAdapter(adapter);
		quantity.setOnItemSelectedListener(new SpinnerSelect(price, item));
		
		price.setText(""+((double)item.getOrderPrice()/100));
		item.setOrderTotalPrice(item.getOrderPrice());

		initExtras();


		addCart.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				OzveriMenuApplicationObject.orders.add(item.getCopy());
	
				Context context = getApplicationContext();
				CharSequence text = "Siparisiniz eklendi. ";
				int duration = Toast.LENGTH_SHORT;

				Toast toast = Toast.makeText(context, text, duration);
				toast.show();

			}
		});
		super.onCreate(savedInstanceState);
	}

	private class RadioListener implements OnCheckedChangeListener{
		public int id;


		public RadioListener(int Id) {
			id = Id;
		}
		@Override
		public void onCheckedChanged(CompoundButton buttonView,	boolean isChecked) {

			if(id == -1)
				return;
			if(isChecked){
				if(item.getExtraList()==null){
					item.setExtraList(new Hashtable<Integer, Integer>());
				}
				item.getExtraList().put(id, 1);
				Log.w("nihahahah","checked");

			}

			else{
				Log.w("nihahahah","unchecked");
				item.getExtraList().remove(id);
			}

		}

	}
	
	
	
	class SpinnerSelect implements OnItemSelectedListener {
		TextView price;
		MenuOrderItem item;
		public SpinnerSelect(TextView price, MenuOrderItem item) {
			this.price = price;
			this.item = item;
		}

		@Override
		public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {
			item.setOrderQuantity(arg2+1);
			
		}
		@Override
		public void onNothingSelected(AdapterView<?> arg0) {
			// TODO Auto-generated method stub
			
		}
	}


	private class CheckBoxListener implements OnCheckedChangeListener{

		public int Id;

		public CheckBoxListener(int id) {
			Id = id;
		}

		@Override
		public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
			if(isChecked){

				if(item.getExtraList()==null){
					item.setExtraList(new Hashtable<Integer, Integer>());
				}
				item.getExtraList().put(Id, 1);

			}

			else{
				item.getExtraList().remove(Id);
			}

			calculatePrice();
		}

	}



	private class MultiListener implements OnItemSelectedListener{
		int Id;

		public MultiListener(int id) {
			Id = id;
		}

		@Override
		public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {
			Log.w("position",""+arg2);
			if (arg2 == 0) {
				item.getExtraList().remove(Id);
			}
			else{
				item.getExtraList().put(Id, arg2);	
			}
				
			
			calculatePrice();
			
		}

		@Override
		public void onNothingSelected(AdapterView<?> arg0) {
			// TODO Auto-generated method stub
			
		}

	}




	private void initExtras() {

		item.setExtraList(new Hashtable<Integer, Integer>()); 

		if (item.getExtras() != null && item.getExtras().size() > 0) {
			for (int i = 0; i < item.getExtras().size(); i++) {
				MenuOrderItemExtras currExtra = item.getExtras().get(i);
				if(currExtra.getGroupId() == 0)// a normal extra
				{

					if (currExtra.getQuantityType() == MenuOrderItemExtras.SINGLE) {
						if(checklist == null){
							checklist = new ArrayList<CheckBox>();
						}
						CheckBox chk=new CheckBox(this);  
						chk.setText(currExtra.getName()); 
						checklist.add(chk);
						chk.setOnCheckedChangeListener(new CheckBoxListener(currExtra.getId()));

					}
					else{
						LayoutInflater inflater = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
						LinearLayout itemLayout = (LinearLayout) inflater.inflate(R.layout.multiselectextrarow, null, false);
						LinearLayout.LayoutParams layoutparams = new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT );
						layoutparams.setMargins(10, 10, 10, 10);
						itemLayout.setLayoutParams(layoutparams);

						TextView name = (TextView) itemLayout.findViewById(R.id.multiextra_name_txt);
						name.setText(currExtra.getName());
						name.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 20);

						Spinner quantity = (Spinner) itemLayout.findViewById(R.id.multiextra_quantity_spinner);
						String[] np = new String[26];
						for(int j=0;j<=25;j++){
							np[j]=Integer.toString(j);
						}
						
						ArrayAdapter <String> adapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.spinner_item_text, np);
						quantity.setAdapter(adapter);
					
						quantity.setOnItemSelectedListener(new MultiListener(currExtra.getId()));
	
						if(multilist== null)
							multilist = new ArrayList<LinearLayout>();
						multilist.add(itemLayout);


					}




				}
				else
				{
					if (radioGroups != null) {
						if(radioGroups.containsKey(currExtra.getGroupId())){
							RadioGroup rg = radioGroups.get(currExtra.getGroupId());
							RadioButton rb  = new RadioButton(this);
							LinearLayout.LayoutParams layoutParams = new RadioGroup.LayoutParams(
									RadioGroup.LayoutParams.WRAP_CONTENT,
									RadioGroup.LayoutParams.WRAP_CONTENT);
							layoutParams.setMargins(10, 10, 10, 10);
							rg.addView(rb,0, layoutParams);
							rb.setText(currExtra.getName());
							rb.setOnCheckedChangeListener(new RadioListener(currExtra.getId()));
						}
						else
						{
							if(radioGroupNames == null)
								radioGroupNames = new ArrayList<String>(); 
							radioGroupNames.add(currExtra.getGroupName());
							RadioGroup rg = new RadioGroup(this);
							rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {

								@Override
								public void onCheckedChanged(RadioGroup group, int checkedId) {
									calculatePrice();

								}

							});
							rg.setOrientation(RadioGroup.HORIZONTAL);
							radioGroups.put(currExtra.getGroupId(), rg);

							RadioButton rb  = new RadioButton(this);
							LinearLayout.LayoutParams layoutParams = new RadioGroup.LayoutParams(
									RadioGroup.LayoutParams.WRAP_CONTENT,
									RadioGroup.LayoutParams.WRAP_CONTENT);
							layoutParams.setMargins(10, 10, 10, 10);
							rg.addView(rb,0, layoutParams);
							rb.setText(currExtra.getName());
							rb.setOnCheckedChangeListener(new RadioListener(currExtra.getId()));
						}
					}
					else{

						if(radioGroupNames == null)
							radioGroupNames = new ArrayList<String>();
						radioGroups = new Hashtable<Integer, RadioGroup>();
						radioGroupNames.add(currExtra.getGroupName());
						RadioGroup rg = new RadioGroup(this);
						rg.setOrientation(RadioGroup.HORIZONTAL);
						rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {

							@Override
							public void onCheckedChanged(RadioGroup group, int checkedId) {
								calculatePrice();

							}

						});
						radioGroups.put(currExtra.getGroupId(), rg);

						RadioButton rbN  = new RadioButton(this);
						LinearLayout.LayoutParams layoutParamsN = new RadioGroup.LayoutParams(
								RadioGroup.LayoutParams.WRAP_CONTENT,
								RadioGroup.LayoutParams.WRAP_CONTENT);
						layoutParamsN.setMargins(10, 10, 10, 10);
						rg.addView(rbN,0, layoutParamsN);
						rbN.setText("Normal");
						rbN.setOnCheckedChangeListener(new RadioListener(-1));

						RadioButton rb  = new RadioButton(this);
						LinearLayout.LayoutParams layoutParams = new RadioGroup.LayoutParams(
								RadioGroup.LayoutParams.WRAP_CONTENT,
								RadioGroup.LayoutParams.WRAP_CONTENT);
						layoutParams.setMargins(10, 10, 10, 10);
						rg.addView(rb,0, layoutParams);
						rb.setText(currExtra.getName());
						rb.setOnCheckedChangeListener(new RadioListener(currExtra.getId()));


					}
				}


			}

			int radioCount =0;
			for (RadioGroup group : radioGroups.values()) {
				TextView head = new TextView(getApplicationContext());
				head.setText(radioGroupNames.get(radioCount));
				head.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 20);
				head.setPadding(10, 10, 10, 10);
				extrasMain.addView(head);
				extrasMain.addView(group);
				radioCount++;

			}

			View line = new View(getApplicationContext());
			LayoutParams lineLayoutParams = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, 2);
			lineLayoutParams.setMargins(100, 10, 100, 10);
			line.setLayoutParams(lineLayoutParams);
			line.setBackgroundColor(R.color.gold1);
			extrasMain.addView(line);


			for (LinearLayout multi : multilist) {
				extrasMain.addView(multi);

			}

			View line2 = new View(getApplicationContext());
			LayoutParams lineLayoutParams2 = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, 2);
			lineLayoutParams2.setMargins(100, 10, 100, 10);
			line2.setLayoutParams(lineLayoutParams2);
			line2.setBackgroundColor(R.color.gold1);
			extrasMain.addView(line2);

			//			for (CheckBox check : checklist) {
			//				extrasGrid.addView(check);
			//			}

			extrasGrid.setAdapter(new CheckBoxGridAdapter(checklist));


		}

	}


	private void calculatePrice(){

		if(item.getExtraList().size()>0){
			int extraPrice = 0;
			for (int i = 0; i < item.getExtraList().keySet().toArray().length; i++) {
				int key = (Integer)(item.getExtraList().keySet().toArray()[i]);
				int unitPrice = 0;
				for (int j = 0; j < item.getExtras().size(); j++) {
					if (item.getExtras().get(j).getId() == key) {
						unitPrice = item.getExtras().get(j).getPrice();
						break;

					}

				}				
				extraPrice += unitPrice*item.getExtraList().get(key);


			}
			price.setText(""+((((double)extraPrice)+item.getOrderPrice())/100));
			item.setOrderTotalPrice(extraPrice+item.getOrderPrice());

		}
		else{
			price.setText(""+(double)item.getOrderPrice() / 100);
			item.setOrderTotalPrice(item.getOrderPrice());
			
		}

	}

}
